package org.hadoop;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;

import java.io.IOException;

public class Demo02ListFiles {
    public static void main(String[] args) {
        FileSystem fs = null;
        try {
            // 设置 Hadoop 用户名
            System.setProperty("HADOOP_USER_NAME", "hadoop");
            // 创建 Hadoop 配置对象
            Configuration config = new Configuration();
            config.set("fs.defaultFS", "hdfs://192.168.56.102:8020");
            // 获取 FileSystem 实例
            fs = FileSystem.get(config);
            // 列出 HDFS 上的文件
            RemoteIterator<LocatedFileStatus> files = fs.listFiles(new Path("/"), true);
            // 遍历并输出文件信息
            while (files.hasNext()) {
                LocatedFileStatus file = files.next();
                System.out.println(file.getPermission() + " " + file.getPath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 确保在完成后关闭 FileSystem 实例
            try {
                if (fs != null) fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}